package leetcode.day_2020_2021_1_25_2021_1_31;

import java.util.HashMap;
import java.util.Map;

/**
 * 13. 罗马数字转整数
 * https://leetcode-cn.com/problems/roman-to-integer/
 */
public class LeetCode0013 {
    public static void main(String[] args) {
        System.out.println(romanToInt("III"));
        System.out.println(romanToInt("IV"));
        System.out.println(romanToInt("IX"));
    }

    public static int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);

        int sum = 0;
        int i = s.length()-1;
        while(i >= 0) {
            if (i==0) {
                sum = sum + map.get(s.charAt(i));
                i -= 1;
            } else {
                boolean flag = ((map.get(s.charAt(i))-map.get(s.charAt(i-1))) > 0) ? true : false;
                sum = sum + (flag ? (map.get(s.charAt(i))-map.get(s.charAt(i-1))) : map.get(s.charAt(i)));
                i = flag ? (i-2) : (i-1);
            }
        }
        return sum;
    }
}
